﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
using System.Web;
using Slam.FieldTypes;

namespace SlamCms.SharePoint.FieldTypes
{	
	public partial class FilteredLookupFieldControl : SlamFieldControl
	{
		protected DropDownList ddlListItems;

		protected override string DefaultTemplateName
		{
			get
			{
				return "SlamCMSFilteredLookupFieldControl";
			}
		}

		public string FieldValueType
		{
			get;
			set;
		}

		public override object Value
		{
			get
			{
				this.EnsureChildControls();
				object value = null;
				int valueId = 0;
				Int32.TryParse(ddlListItems.SelectedValue, out valueId);
				if (FieldValueType.Equals("Item SLAM ID") || valueId > 0)
				{
					switch (FieldValueType)
					{
						case "Lookup Value":
							value = new SPFieldLookupValue(valueId, ddlListItems.SelectedItem.Text);
							break;
						case "Item ID":
							value = valueId;
							break;
						case "Item Text":
							value = ddlListItems.SelectedItem.Text;
							break;
						case "Item SLAM ID":
							value = ddlListItems.SelectedValue;
							break;
					}
				}
				return value;
			}
			set
			{
				this.EnsureChildControls();
				ListItem item = null;
				switch (FieldValueType)
				{
					case "Lookup Value":
						SPFieldLookupValue fieldValue = new SPFieldLookupValue();
						if (value != null)
						{
							fieldValue = new SPFieldLookupValue(Convert.ToString(value));
						}

						if (!String.IsNullOrEmpty(fieldValue.LookupValue))
						{
							item = ddlListItems.Items.FindByValue(fieldValue.LookupId.ToString());
							if (item != null)
							{
								ddlListItems.SelectedIndex = -1;
								item.Selected = true;
							}
						}
						break;
					case "Item Text":
						item = ddlListItems.Items.FindByText(value.ToString());
						if (item != null)
						{
							ddlListItems.SelectedIndex = -1;
							item.Selected = true;
						}
						break;
					default:
						item = ddlListItems.Items.FindByValue(value.ToString());
						if (item != null)
						{
							ddlListItems.SelectedIndex = -1;
							item.Selected = true;
						}
						break;
				}
				
			}
		}

		private string lookupList;

		public string LookupList
		{
			get { return lookupList; }
			set { lookupList = value; }
		}

		private string lookupFieldName;

		public string LookupField
		{
			get { return lookupFieldName; }
			set { lookupFieldName = value; }
		}

		private string filterQuery;

		public string FilterQuery
		{
			get { return filterQuery; }
			set { filterQuery = value; }
		}

		private bool defaultToFirstValue;
		public bool DefaultToFirstValue
		{
			get { return defaultToFirstValue; }
			set { defaultToFirstValue = value; }
		}

		[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
		public override void Validate()
		{
			if ((base.ControlMode != SPControlMode.Display) && base.IsValid && base.Field.Required && !defaultToFirstValue)
			{
				base.Validate();
				if (ddlListItems.SelectedIndex == 0)
				{
					base.IsValid = false;
					base.ErrorMessage = SPResource.GetString("MissingRequiredField", new object[0]);
				}
			}
		}

		protected override void CreateChildControls()
		{
			if (Field == null)
				return;

			base.CreateChildControls();

			if (ControlMode == SPControlMode.Display)
				return;

			if (!base.IsFieldValueCached)
			{
				ddlListItems = (DropDownList)TemplateContainer.FindControl("ddlListItems");

				SPQuery query = new SPQuery();
				query.Query = this.FilterQuery;

				//Find the list in any site in this site collection that
				//corresponds to the Lookup List ID

				SPList list = null;

				SPWeb site = SPControl.GetContextWeb(HttpContext.Current);
				SPSecurity.RunWithElevatedPrivileges(delegate()
				{
					using (SPSite elevatedSite = new SPSite(site.Site.ID))
					{
						foreach (SPWeb elevatedWeb in elevatedSite.AllWebs)
						{
							try
							{
								list = elevatedWeb.Lists[new Guid(LookupList)];
								if (list != null)
								{
									SPListItemCollection listItems = list.Items;
									if (!String.IsNullOrEmpty(FilterQuery))
									{
										listItems = list.GetItems(query);
									}
									ddlListItems.DataTextField = LookupField;
									if (FieldValueType.Equals("Item SLAM ID"))
										ddlListItems.DataValueField = "SLAM_x0020_ID";
									else
										ddlListItems.DataValueField = "ID";
									ddlListItems.DataSource = listItems.GetDataTable();
									ddlListItems.DataBind();
										
									if (!defaultToFirstValue)
									{
										ddlListItems.Items.Insert(0, new ListItem("(None)", "-1"));
									}

									if (ItemFieldValue != null)
									{
										Value = ItemFieldValue;
									}
									break;
								}
							}
							catch
							{
								//It is reasonable to assume SharePoint will throw an exception
								//as usual if the list isn't found instead of returning null
							}
						}
					}
				});
			}
		}
	}
}
